package dao

import (
	"github.com/micro/go-micro/v2/errors"
	"golang.org/x/crypto/bcrypt"
	"micro-grpc-server/library/encrypt"
	"micro-grpc-server/library/rand"
	"micro-grpc-server/services/user/internal/models"
	pb "micro-grpc-server/services/user/proto"
	"time"
)

// 通过密码登录
func (d *UserDao) LoginByPassword(rq *pb.LoginRequest) (*models.Identity, error) {
	var identity = &models.Identity{}
	err := d.Db.Where("account = ? or phone = ?", rq.Account, rq.Account).First(&identity).Error
	if err != nil {
		return nil, errors.BadRequest(d.conf.ServerName, "账号或密码错误")
	}

	if err := bcrypt.CompareHashAndPassword([]byte(identity.Password), []byte(rq.Password)); err != nil {
		return nil, errors.BadRequest(d.conf.ServerName, "账号或密码错误")
	}

	return identity, nil
}

// 生成token
func (d *UserDao) GenerateToken(identity *models.Identity) (token *models.Token, accessToken string, err error) {
	token, err = d.createToken(identity)
	if err != nil {
		return
	}
	var generateRequest = &encrypt.GenerateTokenRequest{
		UserId:       token.UserId,
		AccessToken:  token.AccessToken,
		RefreshToken: token.RefreshToken,
		TimeExpired:  token.TimeExpired,
		Avatar:       identity.Avatar,
		Name:         identity.Name,
	}
	accessToken, err = encrypt.GenerateToken(generateRequest, d.conf.Encrypt.TokenSalt)
	if err != nil {
		return
	}

	return
}

// 生成token记录
func (d *UserDao) createToken(identity *models.Identity) (*models.Token, error) {
	var now = time.Now().Unix()
	token := &models.Token{
		UserId:       identity.Id,
		AccessToken:  rand.RandomString(36),
		RefreshToken: rand.RandomString(32),
		TimeCreate:   now,
		TimeExpired:  now + 3600*24,
	}
	if err := d.Db.Save(token).Error; err != nil {
		return nil, err
	}
	return token, nil
}
